package mirfordevoservice.system.GameCenter;

import publicPackage.item.Items;
import mirfordevoservice.system.contasnt.GameConstant;
import publicPackage.human.*;

import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import static mirfordevoservice.system.contasnt.GameConstant.CacheCenter.HUMAN_EXP;
import static mirfordevoservice.system.contasnt.GameConstant.GameDataStream.*;
import static mirfordevoservice.system.contasnt.GameConstant.GameSession.ONLINE_HUMAN_SESSION;
import static mirfordevoservice.system.contasnt.GameConstant.GameSession.ONLINE_ROLE_SESSION;

/**
 * Created by Heart!
 *
 * @Author ZhangChaoJian
 * @Date ${Date}-19:32
 * Wants More Then Try Hard More!
 */
public class GameDataManager {
    private static GameDataManager ourInstance = new GameDataManager();

    public static GameDataManager getInstance() {
        return ourInstance;
    }

    private GameDataManager() {
    }

    /**
     * 创建新角色
     *
     * @param user_enter_msg
     * @return
     */
    public boolean createNewUserFormEnterPage(Map<String, String> user_enter_msg) {
        if (!COUNT_ROLES.containsKey(user_enter_msg.get("username"))) {
            Role new_role = new Role();
            new_role.setUser_count(user_enter_msg.get("username"));
            new_role.setPassword(user_enter_msg.get("password"));
            new_role.setCanLogin(true);//新号可以登录
            HumanData humanData = new HumanData();
            new_role.setHumanData_one(humanData);
            new_role.setHumanData_two(humanData);
            new_role.setServerName(1);
            new_role.setUserID(getRandomIDUtil());
            new_role.setAnswer_one(user_enter_msg.get("answer_one"));
            new_role.setAnswer_two(user_enter_msg.get("answer_two"));
            new_role.setQuestion_one(user_enter_msg.get("question_one"));
            new_role.setQuestion_two(user_enter_msg.get("question_two"));
            new_role.setCell_phone(Long.valueOf(user_enter_msg.get("cell_phone")));
            if ("".equalsIgnoreCase(user_enter_msg.get("phone"))) {
                new_role.setPhone(0);
            } else {
                new_role.setPhone(Long.valueOf(user_enter_msg.get("phone")));
            }
            new_role.setPlayer_name(user_enter_msg.get("name"));
            COUNT_ROLES.put(new_role.getUser_count(), new_role.getUserID());
            ALL_ROLES.put(new_role.getUserID(), new_role);
            return true;
        } else {
            System.err.println("新建角色时出错，重复账号");
            return false;
        }
    }

    /**
     * 创建新的人物并返回消息
     *
     * @param name
     * @param job
     * @param sex
     * @param rid
     * @param place
     * @return
     */
    public Role createNewHumanAndCallBack(String name, int job, int sex, Long rid, int place) {
        Role role = DataCenter.getInstance().getRoleByID(rid);
        if (NAME_LIST.contains(name)) {
            System.err.println("玩家已存在");
            return role;
        }
        if (place == 1) {
            HumanData humanData = new HumanData();
            humanData.setLocation(place);
            humanData.setFlyLevel(0);
            Map<Long, Hero> heroMap = new HashMap<>();
            humanData.setHeroMap(heroMap);
            humanData.setJob(job);
            humanData.setLevel(1);
            humanData.setMainRoleID(getRandomIDUtil());
            Map<Integer, Items> integerItemsMap = new HashMap<>();
            humanData.setWearingMap(integerItemsMap);
            humanData.setName(name);
            humanData.setSex(sex);
            humanData.setHumanBag(new Bag());
            humanData.setBagMaxSize(40);
            humanData.setCurrentEXP(0);
            humanData.setMaxEXP(HUMAN_EXP.get(1));
            humanData.setMapID(0);
            humanData.setSaftyPlace(true);
            humanData.setVipLevel(0);
            giveBaseStateForJob(humanData, job);
            role.setHumanData_one(humanData);
        } else {
            HumanData humanData = new HumanData();
            humanData.setLocation(place);
            humanData.setFlyLevel(0);
            Map<Long, Hero> heroMap = new HashMap<>();
            humanData.setHeroMap(heroMap);
            humanData.setJob(job);
            humanData.setLevel(1);
            humanData.setMainRoleID(getRandomIDUtil());
            Map<Integer, Items> integerItemsMap = new HashMap<>();
            humanData.setWearingMap(integerItemsMap);
            humanData.setName(name);
            humanData.setSex(sex);
            humanData.setHumanBag(new Bag());
            humanData.setBagMaxSize(40);
            humanData.setCurrentEXP(0);
            humanData.setMaxEXP(HUMAN_EXP.get(1));
            humanData.setMapID(0);
            humanData.setSaftyPlace(true);
            humanData.setVipLevel(0);
            giveBaseStateForJob(humanData, job);
            role.setHumanData_two(humanData);
        }
        NAME_LIST.add(name);
        return role;
    }

    /**
     * 根据职业赋予初始属性
     *
     * @param humanData
     * @param job
     */
    private void giveBaseStateForJob(HumanData humanData, int job) {
        HumanState humanState = new HumanState();
        switch (job) {
            case GameConstant.HumanType.Job.TAOIST: {
                /**
                 * 血魔初值
                 */
                int HP = DataCenter.getInstance().getHumanConfigByKeyName("humanHP", "taoist01级");
                int MP = DataCenter.getInstance().getHumanConfigByKeyName("MP", "道士MP1");
                humanState.setMaxHP(HP);
                humanState.setCurHP(HP);
                humanState.setMaxMP(MP);
                humanState.setCurMP(MP);
                humanState.setMPHeal(2);//每回合回蓝量
                humanState.setHPHeal(1);//每回合回血量
                humanState.setATKSpeed(5);//攻速
                humanState.setHit(1);//准确
                humanState.setMaxDef(2);//最大物防
                humanState.setMinDef(1);//最小物防;
                humanState.setMaxMagicDef(1);//最大魔防
                humanState.setMinMagicDef(0);//最小魔防
                humanState.setMaxMagicATK(0);//最大魔法力
                humanState.setMinMagicATK(0);//最小魔法力
                humanState.setMaxPhyATK(1);//最大攻击
                humanState.setMinPhyATK(0);//最小攻击力
                humanState.setMaxTaoistATK(2);//最大道术
                humanState.setMinTaoistATK(1);//最小道术
                humanData.setHumanState(humanState);
                break;
            }
            case GameConstant.HumanType.Job.WARRIOR: {
                /**
                 * 血魔初值
                 */
                int HP = DataCenter.getInstance().getHumanConfigByKeyName("humanHP", "warrior01级");
                int MP = DataCenter.getInstance().getHumanConfigByKeyName("MP", "战士MP1");
                humanState.setMaxHP(HP);
                humanState.setCurHP(HP);
                humanState.setMaxMP(MP);
                humanState.setCurMP(MP);
                humanState.setMPHeal(1);//每回合回蓝量
                humanState.setHPHeal(2);//每回合回血量
                humanState.setATKSpeed(6);//攻速
                humanState.setHit(1);//准确
                humanState.setMaxDef(3);//最大物防
                humanState.setMinDef(2);//最小物防;
                humanState.setMaxMagicDef(2);//最大魔防
                humanState.setMinMagicDef(1);//最小魔防
                humanState.setMaxMagicATK(0);//最大魔法力
                humanState.setMinMagicATK(0);//最小魔法力
                humanState.setMaxPhyATK(2);//最大攻击
                humanState.setMinPhyATK(1);//最小攻击力
                humanState.setMaxTaoistATK(0);//最大道术
                humanState.setMinTaoistATK(0);//最小道术
                humanData.setHumanState(humanState);
                break;
            }
            case GameConstant.HumanType.Job.WIZARD: {
                /**
                 * 血魔初值
                 */
                int HP = DataCenter.getInstance().getHumanConfigByKeyName("humanHP", "wizard01级");
                int MP = DataCenter.getInstance().getHumanConfigByKeyName("MP", "法师MP1");
                humanState.setMaxHP(HP);
                humanState.setCurHP(HP);
                humanState.setMaxMP(MP);
                humanState.setCurMP(MP);
                humanState.setMPHeal(3);//每回合回蓝量
                humanState.setHPHeal(1);//每回合回血量
                humanState.setATKSpeed(5);//攻速
                humanState.setHit(1);//准确
                humanState.setMaxDef(1);//最大物防
                humanState.setMinDef(1);//最小物防;
                humanState.setMaxMagicDef(2);//最大魔防
                humanState.setMinMagicDef(1);//最小魔防
                humanState.setMaxMagicATK(1);//最大魔法力
                humanState.setMinMagicATK(0);//最小魔法力
                humanState.setMaxPhyATK(1);//最大攻击
                humanState.setMinPhyATK(0);//最小攻击力
                humanState.setMaxTaoistATK(0);//最大道术
                humanState.setMinTaoistATK(0);//最小道术
                humanData.setHumanState(humanState);
                break;
            }
        }
    }

    /**
     * 检测是否可以修改密码
     *
     * @param change_password
     * @return
     */
    public int checkChangUserLoginPassword(String[] change_password) {
        if (COUNT_ROLES.containsKey(change_password[0])) {
            Role change_role = ALL_ROLES.get(COUNT_ROLES.get(change_password[0]));
            if (change_role == null) {
                return 1;//读取账户失败
            }
            if (change_password[1].equalsIgnoreCase(change_role.getPassword())) {
                change_role.setPassword(change_password[2]);
                System.err.printf("敏感操作-----玩家" + change_role.getUser_count() + "修改新密码为" + change_role.getPassword());
                DataCenter.getInstance().savingData();
                return 2;//成功修改
            } else {
                return 3;//旧密码不匹配
            }
        } else {
            return 4;//用户不存在
        }

    }

    /**
     * 玩家登陆方法
     *
     * @param username
     * @param password
     * @return
     */
    public Role CheckForLoginToSelectPage(String username, char[] password) {
        if (COUNT_ROLES.containsKey(username)) {
            String password_role = ALL_ROLES.get(COUNT_ROLES.get(username)).getPassword();
            String password_line = String.valueOf(password);
            if (password_role.equalsIgnoreCase(password_line)) {
                return ALL_ROLES.get(COUNT_ROLES.get(username));
            }
            return null;
        } else {
            return null;
        }
    }

    /**
     * 执行删除玩家人物的信息
     *
     * @param id
     * @param select_human
     * @return
     */
    public Role deleteHumanByRole(Long id, int select_human) {
        Role role = DataCenter.getInstance().getRoleByID(id);
        if (role == null) {
            System.err.println("玩家信息未找到");
            return null;
        }
        if (select_human == 1) {
            NAME_LIST.remove(role.getHumanData_one().getName());
            HumanData humanData = new HumanData();
            HumanData humanData_two = role.getHumanData_two();
            humanData_two.setLocation(1);
            role.setHumanData_one(humanData_two);//将第二位角色变为第一位
            role.setHumanData_two(humanData);//将第二位置空
        } else {
            NAME_LIST.remove(role.getHumanData_two().getName());
            HumanData humanData = new HumanData();
            role.setHumanData_two(humanData);
        }
        DataCenter.getInstance().savingBeforeExit();
        return role;
    }

    /**
     * ID生成工具
     *
     * @return
     */
    public static Long getRandomIDUtil() {
        long temp = System.currentTimeMillis();
        AtomicInteger IDInteger = new AtomicInteger(1);
        long total = temp + IDInteger.addAndGet(1);
        return total;
    }

    /**
     * 顶号逻辑
     *
     * @param other
     */
    public void reConnected(Socket other) {
        DataCenter.getInstance().savingData();//提前保存信息
        try {
            System.out.println("顶号登陆事件!!" + other.getLocalSocketAddress());
            other.close();//关闭前一次的会话链接
            ONLINE_ROLE_SESSION.remove(other);//移除上次登录的会话
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取进入游戏的人物信息，存入玩家在线会话
     *
     * @param place
     * @param uid
     * @return
     */
    public HumanData enterGameHuman(Integer place, Long uid) {
        Role role = DataCenter.getInstance().getRoleByID(uid);
        HumanData humanData = role.getHumanData(place);
        if (humanData.getMainRoleID() == null) {
            System.out.println("传入参数错误...");
            return null;
        }
        ONLINE_HUMAN_SESSION.put(humanData.getMainRoleID(), humanData);//存入会话缓存
        return humanData;
    }
}
